package org.kalai.unifypay.mins;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.kalai.unifypay.Constant;
import org.kalai.unifypay.util.CipherUtils;
import org.kalai.unifypay.util.DateUtil;
import org.kalai.unifypay.util.HttpUtil;
import org.kalai.unifypay.util.StringUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 民生银行相关工具类
 * @author Renne66
 *
 */
public class MinsUtil {
	private static final Logger logger = Logger.getLogger(MinsUtil.class);
	
	public static String sendPost(Map<String, Object> params, String tranxSN, String tranCode){
		String aesKey = CipherUtils.encryptMD5(String.valueOf(Math.random())).substring(8, 24);
		String xmlMessage = buildMsg(params);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cooperator", Constant.MS_COOPERATOR);//合作方标识
		map.put("tranCode", tranCode);//交易服务码
		map.put("reqMsgId", tranxSN);//请求流水号（订单号）
		map.put("signData", CipherUtils.encryptBase64(CipherUtils.signRSA(xmlMessage)));//请求报文签名
		map.put("encryptData", CipherUtils.encryptBase64(CipherUtils.encryptAES(xmlMessage, aesKey)));//加密后的请求报文
		map.put("encryptKey", CipherUtils.encryptBase64(CipherUtils.encryptRSA(aesKey)));//加密后的AES对称密钥
		map.put("callBack", Constant.MS_NOTIFY_URL);//回调地址
		String result = HttpUtil.sendHttpsPost(Constant.MS_URL, map);
		JSONObject jo = JSON.parseObject(result);
		if(jo != null){
			String encryptData = jo.getString("encryptData");
			String encryptKey = jo.getString("encryptKey");
			String signData = jo.getString("signData");
			tranCode = jo.getString("tranCode");
			tranxSN = jo.getString("reqMsgId");
			aesKey = CipherUtils.decryptRSA(CipherUtils.decryptBase64(encryptKey));
			xmlMessage = CipherUtils.decryptAES(CipherUtils.decryptBase64(encryptData), aesKey);
			boolean flag = CipherUtils.designRSA(CipherUtils.decryptBase64(signData), xmlMessage);
			if (flag) {
				return xmlMessage;
			}else{
				logger.error("民生银行支付验证签名失败:" + tranxSN);
			}
		}else{
			logger.error("民生银行支付解析返回值失败["+result+"]");
		}
		return null;
	}
	
	public static Map<String, Object> parseRet(String xmlMessage){
		if (xmlMessage != null) {
			Map<String, Object> retMap = new HashMap<>();
			String respCode = xmlMessage.substring(xmlMessage.indexOf("<respCode>") + 10, xmlMessage.indexOf("</respCode>"));
			retMap.put("respCode", "000000".equals(respCode) ? "00" : respCode);
			retMap.put("respDesc", xmlMessage.substring(xmlMessage.indexOf("<respMsg>") + 9, xmlMessage.indexOf("</respMsg>")));
			return retMap;
		}else{
			return  new HashMap<>();
		}
	}
	
	private static String buildMsg(Map<String, Object> params){
		Document doc = DocumentHelper.createDocument();
		Element merchant = doc.addElement("merchant");
		Element head = merchant.addElement("head");
		head.addElement("version").setText("1.0.0");
		head.addElement("msgType").setText("01");
		head.addElement("reqDate").setText(DateUtil.formatNow("yyyyMMddHHmmss"));
		Element body = merchant.addElement("body");
		for (Map.Entry<String, Object> entry : params.entrySet()) {
			body.addElement(entry.getKey()).setText(String.valueOf(entry.getValue()));
		}
		return StringUtil.xmlToStr(doc);
	}
}
